package scenic.study.arithmetic.queue;

import java.util.Iterator;

/**
 * Created by scenic on 2017/2/15.
 */
public class ArrayQueue<T> implements QueueInterface<T>{
    private T[] data ;
    private int headerIndex;
    private int lastIndex;
    public ArrayQueue(){
        data = (T[]) new Object[10];
    }

    public void resize(int length) {
        T[] tmp = (T[]) new Object[length];

        for (int i = headerIndex; i < lastIndex; i++) {
            tmp[i - headerIndex] = data[i];
        }

        lastIndex = lastIndex - headerIndex;
        headerIndex = 0;
        data = tmp;
    }

    @Override
    public void enqueue(T t) {
        if(lastIndex >= data.length){
            resize(Math.max(data.length,size() * 2));
        }
        data[lastIndex] = t;
        lastIndex++;
    }

    @Override
    public T dequeue() {
        T t = data[headerIndex];
        headerIndex++;
        if(headerIndex == lastIndex){
            resize(data.length);
        }
        return t;
    }

    @Override
    public int size() {
        return lastIndex - headerIndex;
    }

    @Override
    public boolean isEmpty() {
        return size() == 0 ;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            int start = headerIndex;
            int end = lastIndex;
            @Override
            public boolean hasNext() {
                return end > start;
            }

            @Override
            public T next() {
                return data[start++];
            }
        };
    }
}
